package com.ikas.autumn.iec104.common.handle;

import com.alibaba.fastjson.serializer.*;
import com.ikas.autumn.iec104.common.enums.ConfigStateEnum;
import com.ikas.autumn.iec104.common.enums.GlobalConstants;

import java.lang.reflect.Type;
import java.text.DecimalFormat;
import java.util.Date;

/**
 * JSON序列，针对fastjson
 * @ClassName: JsonSerialize
 * @author HXH
 * @version 1.0.0
 */
public class JsonSerializeHandler {
    private JsonSerializeHandler() {
    }
    private static final SerializeConfig globalInstance = SerializeConfig.getGlobalInstance();
    public static final String DATETIMEFORMATTPL = "yyyy-MM-dd HH:mm:ss";

    static {
        // 配置需要序列的指定类
        globalInstance.put(Double.class, new DoubleSerializerConfig(GlobalConstants.DOUBLE_FORMAT));
        globalInstance.put(ConfigStateEnum.class, EnumStatusSerializer.instance);
        globalInstance.put(Date.class, new SimpleDateFormatSerializer(DATETIMEFORMATTPL));
    }

    public static SerializeConfig instance() {
        return globalInstance;
    }

    /**
     * Double格式保留两位小数点（0.00）
     */
    public static class DoubleSerializerConfig extends DoubleSerializer {
        public DoubleSerializerConfig(DecimalFormat decimalFormat) {
            this.decimalFormat = decimalFormat;
        }

        private final DecimalFormat decimalFormat;

        @Override
        public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) {
            SerializeWriter out = serializer.out;
            if (object == null) {
                out.writeNull(SerializerFeature.WriteNullNumberAsZero);
                return;
            }
            double doubleValue = (Double) object;
            if (Double.isNaN(doubleValue) || Double.isInfinite(doubleValue)) {
                out.writeNull();
            } else {
                if (decimalFormat == null) {
                    out.writeDouble(doubleValue, true);
                } else {
                    String doubleText = decimalFormat.format(doubleValue);
                    out.write("\"" + doubleText + "\"");
                }
            }
        }
    }

    /**
     * 枚举类序列
     */
    public static class EnumStatusSerializer implements ObjectSerializer {

        public static final EnumStatusSerializer instance = new EnumStatusSerializer();

        @Override
        public void write(JSONSerializer serializer, Object object, Object fieldName, Type fieldType, int features) {
            SerializeWriter out = serializer.out;
            if (object instanceof ConfigStateEnum) {
                ConfigStateEnum state = (ConfigStateEnum) object;
                out.write("\"" + state.getValue() + "\"");
            } else {
                out.writeEnum((Enum<?>) object);
            }
        }
    }
}